package algorithm;

import java.util.Arrays;

/**
 * 公共前缀
 *
 * 编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀，返回空字符串 ""。
 * SameChar
 */
public class SamePrefix {




    public String samePrefix(String[] strings){

        boolean flag = checkArray(strings);
        if(flag){
            Arrays.sort(strings);
            int f = strings[0].length();
            int l = strings[strings.length -1].length();
            int min = f;
            if(f > l){
                min = l;
            }
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < min; i++) {
                if (strings[0].charAt(i) == strings[strings.length - 1].charAt(i)) {
                    sb.append(strings[0].charAt(i));
                } else
                    break;
            }
            return sb.toString();
        }
        return "";
    }

    /**
     * 校验数组是否合法
     * @param strings
     * @return
     */
    public boolean checkArray(String[] strings){

        if(strings != null && strings.length > 0){
            for (int i = 0; i < strings.length; i++) {
                if(strings[i] == null || "".equals(strings[i])){
                    return false;
                }
            }
            return true;
        }
        return false;
    }


    public static void main(String[] args) {
        SamePrefix sameChar = new SamePrefix();
        String[] strings = new String[]{"abs","ab","abddd"};
        String st = sameChar.samePrefix(strings);
        System.out.print(st);
    }

}